package main

import (
	"flag"
	"fmt"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/util/homedir"
	"path/filepath"
	"time"
)


import (
	"context"
	"flag"
	"fmt"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/util/homedir"
	"path/filepath"
	"time"
)

func main(){
	fmt.Println(time.Now().Format("2006:01:02 15:04:05")) //格式化日期
	var kubeconfig *string
	var namespacelist = []string{"bcap","cesp","fuxing"}
	if home := homedir.HomeDir();home != ""{
		kubeconfig = flag.String("kubeconfig",filepath.Join(home,".kube","config"),"option absolute path")
	}else {
		kubeconfig = flag.String("kubeconfig","","absolute config file path")
	}

	flag.Parse()
	config,err := clientcmd.BuildConfigFromFlags("",*kubeconfig)
	if err != nil{
		panic(err.Error())
	}
	clientset,err := kubernetes.NewForConfig(config)
	if err!= nil{
		panic(err.Error())
	}
	namespaces,err := clientset.CoreV1().Namespaces().List(context.TODO(),metav1.ListOptions{})
	if err != nil{
		panic(err.Error())
	}
	for _,ns := range namespaces.Items{
		fmt.Println(ns.Name,ns.Namespace)
		result := in(ns.Name,namespacelist)
		if result{
			deployments, err := clientset.AppsV1().Deployments(ns.Name).List(context.TODO(),metav1.ListOptions{})
			if err != nil{
				panic(err.Error())
			}
			for _,dep := range deployments.Items {
				deployment := &dep
				deployment.Spec.Template.ObjectMeta.Labels["restarts"] = fmt.Sprintf("%s", time.Now().Format("20060102150405"))
				_,err := clientset.AppsV1().Deployments(ns.Name).Update(context.TODO(),deployment,metav1.UpdateOptions{})
				if err != nil{
					panic(err.Error())
				}
			}
		}
	}
}

func in(target string, str_arry []string) bool {
	for _,element := range str_arry{
		if target == element{
			return true
		}
	}
	return false
}


